/**
 * 
 */
package hu.gbalage.owlforms.xforms.gen;

import java.util.List;

import hu.gbalage.owlforms.api.Field;
import hu.gbalage.owlforms.api.Form;
import hu.gbalage.owlforms.api.style.FieldOrderProvider;

import org.w3c.dom.Document;

/**
 * @author Grill Balazs (balage.g@gmail.com)
 *
 */
public class SerializeManager {

	final FormSerializer serializer;
	
	public SerializeManager(FormSerializer serializer){
		this.serializer = serializer;
	}
	
	protected SerializationState processForm(Form form, SerializationState state, Boolean selected){
		SerializationState s = serializer.serializeForm(form, state,selected);
		FieldOrderProvider order = form.getStyle().getFieldOrderProvider();
		List<Field> fields = order.orderFields(form.listFields());
		
		
		for(Field f : fields){
			SerializationState s1 = serializer.serializeField(f, s);
			if (f.isComplex()){
				if (f.asComplexField().isImported()){
					serializer.putInputDiv(state);
				}else{
					boolean first = true;
					for(Form frm : f.asComplexField().getContainedForm()){
						processForm(frm,s1,first);
						first = false;
					}
				}
			}
		}
		
		return s;
	}
	
	
	public Document serialize(Form form){
		SerializationState state = serializer.initState(form);
		
		state = processForm(form, state,null);
		
		state = serializer.finalize(state);
		
		return state.getDocument();
	}
	
}
